import { isExternal, toHump } from '@/utils'
import { resolve } from 'path-browserify'
import { h, ref } from 'vue'
import { RouteRecordRaw } from 'vue-router'
import { MenuOption, NIcon } from 'naive-ui'
import SvgIcon from '@/components/SvgIcon/index.vue'

export interface OriginRoute {
    parentPath?: string
    menuUrl: string
    menuName?: string
    routeName?: string
    hidden?: boolean
    outLink?: string
    affix?: boolean
    cacheable?: boolean
    isRootPath?: boolean
    iconPrefix?: string
    icon?: string
    badge?: string | number
    isSingle?: boolean
    localFilePath?: string
    children?: Array<OriginRoute>
}

//处理本地路由
export function processLocalRoutes(routes: Array<any>) {
    // 处理本地路由
    let tempRoutes = routes.filter((r: { name: undefined; meta: any }) => r.name !== undefined &&  JSON.stringify(r.meta) !== '{}')
    let tempChild: Array<any> = JSON.parse(JSON.stringify(tempRoutes))
    tempRoutes.forEach((t: any, index: number) => {
        tempChild[index].children.push(t)
    })
    // 根据权重(weight)进行排序，权重越大越靠前
    tempChild.sort((a:any, b:any) => {
        let aValue = a.meta.weight | 0
        let bValue = b.meta.weight | 0
        if (aValue < bValue) {
            return 1
        } else {
            return -1
        }
    })
    return tempChild
}


export function filterRoutesFromLocalRoutes(
    route: OriginRoute,
    localRoutes: Array<RouteRecordRaw>,
    path = '/'
) {
    const filterRoute = localRoutes.find((it) => {
        return resolve(path, it.path) === route.menuUrl
    })
    if (filterRoute) {
        filterRoute.meta = {
            title: route.menuName,
            affix: !!route.affix,
            cacheable: !!route.cacheable,
            icon: route.icon || 'menu',
            iconPrefix: route.iconPrefix || 'iconfont',
            badge: route.badge,
            hidden: !!route.hidden,
            isRootPath: !!route.isRootPath,
            isSingle: !!route.isSingle,
            ...filterRoute.meta,
        }
        const parentPath = resolve(path, filterRoute.path)
        if (
            Array.isArray(route.children) &&
            route.children.length > 0 &&
            Array.isArray(filterRoute.children) &&
            filterRoute.children.length > 0
        ) {
            const tempChildren: RouteRecordRaw[] = []
            route.children.forEach((it) => {
                const childFilterRoute = filterRoutesFromLocalRoutes(it, filterRoute.children!, parentPath)
                childFilterRoute && tempChildren.push(childFilterRoute)
            })
            filterRoute.children = tempChildren
        }
    }
    return filterRoute
}


export function findAffixedRoutes(routes: Array<RouteRecordRaw>) {
    const temp = [] as Array<RouteRecordRaw>
    routes.forEach((it) => {
        if (it.meta && it.meta.affix) {
            temp.push(it)
        }
    })
    return temp
}

export function findCachedRoutes(routes: Array<RouteRecordRaw>) {
    const temp = [] as Array<string>
    routes.forEach((it) => {
        if (it.name && it.meta && it.meta.cacheable) {
            temp.push(it.name as string)
        }
    })
    return temp
}

export function transfromMenu(originRoutes: Array<RouteRecordRaw>): Array<MenuOption> {
    function getLabel(item: RouteRecordRaw) {
        if (isExternal(item.path as string)) {
            return () =>
                h(
                    'a',
                    {
                        href: item.path,
                        target: '_blank',
                        rel: 'noopenner noreferrer',
                    },
                    (item.meta as any).title
                )
        }
        return item.meta?.title || ''
    }
    if (!originRoutes) {
        return []
    }
    const tempMenus: Array<MenuOption> = []
    originRoutes
        .filter((it) => {
            if (!it.meta) {
                return false
            }
            return !it.meta.hidden
        })
        .forEach((it) => {
            const tempMenu = {
                key: it.path,
                label: getLabel(it),
                icon: renderMenuIcon(
                    it.meta ? (it.meta.iconPrefix ? (it.meta.iconPrefix as string) : 'icon') : 'icon',
                    it.meta?.icon
                ),
            } as MenuOption
            if (it.children) {
                if (it.meta && it.meta.isSingle && it.children.length === 1) {
                    const item = it.children[0]
                    tempMenu.key = resolve(tempMenu.key as string, item.path)
                    tempMenu.label =
                        item.meta && item.meta.title ? getLabel(item as RouteRecordRaw) : tempMenu.label
                    tempMenu.icon =
                        item.meta && item.meta.icon
                            ? renderMenuIcon(
                                item.meta
                                    ? item.meta.iconPrefix
                                        ? (item.meta.iconPrefix as string)
                                        : 'icon'
                                    : 'icon',
                                item.meta?.icon
                            )
                            : tempMenu.icon
                } else {
                    tempMenu.children = transfromMenu(it.children as RouteRecordRaw[])
                }
            }
            tempMenus.push(tempMenu)
        })

    console.log(tempMenus)
    return tempMenus
}

export function renderMenuIcon(iconPrefix: string, icon?: any) {
    if (!icon) {
        return undefined
    }
    return () =>
        h(NIcon, null, {
            default: () =>
                h(SvgIcon, {
                    prefix: iconPrefix,
                    name: icon,
                }),
        })
}
